package com.yjd.comm.system.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.yjd.comm.rpm.RpmServiceKeyEnum;
import com.yjd.comm.system.dto.AdminDataWrap;
import com.yjd.comm.system.dto.OperParamDto;
import com.yjd.comm.system.model.AdminMenuModel;
import com.yjd.comm.system.model.AdminModel;
import com.yjd.comm.system.model.AdminRoleInfoDto;
import com.yjd.comm.system.model.AdminRoleModel;
import com.yjd.comm.system.service.IAdminRoleService;
import com.yjd.comm.system.service.IAdminRoleUserService;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServiceHolder;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.StringUtil;

/**
 * @ClassName: AdminDataUtil
 * @Description: 系统用户工具类
 * @author ready likun_557@163.com
 * @date 2014-8-19 上午11:34:08
 */
public class AdminDataNewUtil {
	public static final String SESSION_SYS_USER = "SESSION_SYS_USER";

	/**
	 * @Title: putSession
	 * @Description: 将系统用户的相关数据放入到session中
	 * @param @param request
	 * @param @param response
	 * @param @param sysUserDataWrap 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	public static void putSession(HttpServletRequest request,
			HttpServletResponse response, AdminDataWrap adminDataWrap) {
		ServletUtil.putSession(request, response, SESSION_SYS_USER,
				adminDataWrap);
	}

	/**
	 * @Title: getSysUserDataWrap
	 * @Description: 获取系统用户相关数据
	 * @param @param request
	 * @param @param response
	 * @param @return 设定文件
	 * @return SysUserDataWrap 返回类型
	 * @throws
	 */
	public static AdminDataWrap getAdminDataWrap(HttpServletRequest request,
			HttpServletResponse response) {
		return (AdminDataWrap) ServletUtil.getSessionAttribute(request,
				response, SESSION_SYS_USER);
	}

	/**
	 * 构建管理员数据
	 * 
	 * @param adminModel
	 * @param adminMenuModels
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static AdminDataWrap buildAdminData(AdminModel adminModel,
			List<AdminRoleInfoDto> roleList, List<AdminMenuModel> adminMenuModels) throws Exception {
		AdminDataWrap adminDataWrap = new AdminDataWrap();
		adminDataWrap.setAdminModel(adminModel);
		adminDataWrap.setRoleList(roleList);
		adminDataWrap.setAdminMenuModels(adminMenuModels);
		String menuIds[] = null;
		// 管理员拥有最高权限
		if (isAdmin(adminModel)) {
			menuIds = new String[adminMenuModels.size()];
			int i = 0;
			for (AdminMenuModel adminMenuModel : adminMenuModels) {
				menuIds[i++] = adminMenuModel.getId().toString();
			}
		} else {
			List<Long> roleIds = new ArrayList<Long>();
			roleIds.addAll(FrameUtil
					.getBeanFieldValues(roleList, "role_id"));
			List<AdminRoleModel> roleInfoList = getRoleService().getArsByIds(roleIds);
			List<String> menuList = new ArrayList<String>();
			for(AdminRoleModel adminRole :roleInfoList){
				String menus = adminRole.getRight();
				if(!StringUtil.isEmpty(menus)){
					String[] menuArry = menus.split(",");
					for(String mid :menuArry){
						menuList.add(mid);
					}
				}
			}
			
			Set<String>  set=new HashSet<String>(); 
			set.addAll(menuList);
			
			menuList = new ArrayList<String>();
			for(java.util.Iterator<String> it= set.iterator();it.hasNext();){
				menuList.add(it.next());
			}
			
			if(menuList.size()>0){
				menuIds = new String[menuList.size()];
				for(int i =0 ;i<menuList.size();i++){
					menuIds[i]=menuList.get(i);
				}
			}
		
		}
		List<AdminMenuModel> userMenuModels = new ArrayList<AdminMenuModel>();

		Map<Long, String> menuIdKeyMap = new HashMap<Long, String>();
		Map<String, Long> menuKeyIdmap = new HashMap<String, Long>();
		Map<String, Map> rootMenuMap = new LinkedHashMap<String, Map>();
		for (AdminMenuModel adminMenuModel : adminMenuModels) {
				if(menuIds!=null){
				for (String string : menuIds) {
					if (adminMenuModel.getId().toString().equals(string)) {
						userMenuModels.add(adminMenuModel);
						String menuKey = (StringUtil.isNotEmpty(adminMenuModel
								.getC()) ? adminMenuModel.getC() : "nav")
								+ ("_" + adminMenuModel.getId());
						menuIdKeyMap.put(adminMenuModel.getId(), menuKey);
						menuKeyIdmap.put(menuKey, adminMenuModel.getId());
						if (adminMenuModel.getLid() == 0) {
							rootMenuMap.put(menuKey,
									FrameUtil.newLinkedHashMap("id", menuKey,
											"name", adminMenuModel.getName()));
						}
					}
				}
			}
		}

		for (Entry<String, Map> entry : rootMenuMap.entrySet()) {
			Map<String, Map> items = new LinkedHashMap<String, Map>();
			for (AdminMenuModel adminMenuModel : userMenuModels) {
				Long menuId = menuKeyIdmap.get(entry.getKey());
				if (menuId.equals(adminMenuModel.getLid())) {
					String key = menuIdKeyMap.get(adminMenuModel.getId());
					items.put(key, FrameUtil.newLinkedHashMap("id", key,
							"name", adminMenuModel.getName(), "parent",
							entry.getKey(), "url",
							ServletUtil.getUrl(adminMenuModel.getUrl())));
				}
			}
			if (items.size() >= 1) {
				entry.getValue().put("items", items);
			}
		}

		adminDataWrap.setUserMenuModels(userMenuModels);
		adminDataWrap.setUserMenuJson(FrameUtil.json(rootMenuMap));
		return adminDataWrap;
	}

	/**
	 * 判断某个用户是否是管理员
	 * 
	 * @param adminModel
	 * @return
	 */
	public static boolean isAdmin(AdminModel adminModel) throws Exception {
		if (adminModel != null
				&& (isRoleFlag(adminModel,0L))) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	private static boolean isRoleFlag(AdminModel adminModel, Long role)
			throws Exception {
		boolean isFlag = false;
		if (adminModel != null&&role!=null) {
			IAdminRoleUserService roleUserService = getRoleUserService();
			List<AdminRoleInfoDto> roleList = roleUserService
					.getAdminRoleByIdList(FrameUtil.newHashMap("amdin_id",
							adminModel.getAdmin_id()));
			
			for(AdminRoleInfoDto roleInfo : roleList){
				if(role.intValue()==roleInfo.getRole_id().intValue()){
					isFlag = true;
					break;
				}
			}
			
			
		}
		return isFlag;
	}

	private static IAdminRoleUserService getRoleUserService() throws Exception {
		return ServiceHolder.getLocalService(IAdminRoleUserService.class, "adminRoleUserService");
	}
	
	private static IAdminRoleService getRoleService() throws Exception {
		return ServiceHolder.getLocalService(IAdminRoleService.class, "adminRoleService");
	}
	
	
	public static Map<String,Long> getRolesForMap(Long admin_id,RpmServiceKeyEnum rpmServiceKeyEnum) throws Exception {
		
       Map<String,Long> roles = new HashMap<String,Long>();
       
		  if(admin_id==null){
			  return roles;
		  }
	  
		List<AdminRoleInfoDto> list = getRoleUserService().getAdminRoleByIdList(FrameUtil.newHashMap("amdin_id",admin_id));
		for(AdminRoleInfoDto roleInfo :list){
			roles.put(roleInfo.getRole_id().toString(), roleInfo.getAdmin_id());
		}
		
		return roles;
	}
	
	/**
	 * 获取操作参数信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public static OperParamDto getOperParamDto(HttpServletRequest request,
			HttpServletResponse response) {
		AdminDataWrap adminDataWrap = getAdminDataWrap(request, response);
		OperParamDto operParamDto = new OperParamDto();
		if (adminDataWrap != null) {
			operParamDto.setAdmin_id(adminDataWrap.getAdminModel()
					.getAdmin_id());
			operParamDto.setUsername(adminDataWrap.getAdminModel()
					.getUsername());
		}
		operParamDto.setIp(ServletUtil.getIpAddr(request));
		return operParamDto;
	}
	
	
	public static Map<String,Long> getRolesForMap(List<AdminRoleInfoDto> list)throws Exception{
		Map<String,Long> roles = new HashMap<String,Long>();
		
		for(AdminRoleInfoDto roleInfo :list){
			roles.put(roleInfo.getRole_id().toString(), roleInfo.getAdmin_id());
		}
		
		return roles;
	}
}
